package com.qili.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.qili.base.entity.CurrentUser;
import com.qili.core.shiro.Principal;
import com.qili.core.utils.DictTypes;
import com.qili.core.utils.DictUtil;
import com.qili.entity.base.BaseDict;
import com.qili.entity.it.dto.ItFormDto;
import com.qili.entity.supervisor.ProjectContract;
import com.qili.entity.supervisor.SupervisorFile;
import com.qili.entity.supervisor.SupervisorFileTemp;
import com.qili.entity.supervisor.SupervisorProject;
import com.qili.entity.supervisor.dto.SupervisorProjectDTO;
import com.qili.entity.supplier.SupplierProject;
import com.qili.entity.sys.SysLog;
import com.qili.mapper.sys.SysLogMapper;
import com.qili.service.it.FormBaseService;
import com.qili.service.it.ItDicService;
import com.qili.service.supervisor.SupervisorFileTempService;
import com.qili.service.supplier.SupplierProjectManagerService;
import com.qili.util.*;
import lombok.extern.java.Log;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author liuyang
 * @date 2021/3/30
 * @description
 */
@Log
@Controller
@RequestMapping("/form/file")
public class FormFileController {

    @Value("${supervisor.fileTempPath}")
    private String fileTempPath;

    @Autowired
    private SupervisorFileTempService fileTempService;

    @Autowired
    private  SupplierProjectManagerService  supplierProjectManagerService;

    @Autowired
    private ItDicService dicService;

    @Autowired
    @Qualifier("FormBaseService")
    private FormBaseService formBaseService;

    @Autowired
    SysLogMapper sysLogMapper;


    /**
     * 保存临时文件,并存入临时file表
     * @param file
     * @param fileData 文件参数载体
     * @return
     */
    @ResponseBody
    @PostMapping("/upload/totemp")
    public JsonUtil upload(MultipartFile file,SupervisorFileTemp fileData)  throws   Exception{
        JsonUtil result = new JsonUtil();
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        System.out.println(file.getOriginalFilename());
        String s = String.valueOf(LocalDateTime.now().toEpochSecond(ZoneOffset.UTC));
        String newFileName = file.getOriginalFilename().substring(0,fileName.lastIndexOf("."))+"_"+ s+suffix;
        System.out.println("新的名字:"+newFileName);
        if(StringUtils.isNotBlank(fileData.getType())) {
            if ("311".equals(fileData.getType())) {
                if(!suffix.toLowerCase().equals(".doc") &&  !suffix.toLowerCase().equals(".docx") ){
                    result.setFlag(false);
                    result.setMsg("请上传doc|docx文件");
                    return result;
                }
                //doc|docx
                if (fileName.indexOf("招标") == -1   ||  fileName.indexOf("说明") == -1 ) {
                    result.setFlag(false);
                    result.setMsg("项目招标说明文件上传的文件名称必须包含“招标“和”说明”字样");
                    return result;
                }
            } else if ("312".equals(fileData.getType())) {

                if(!suffix.toLowerCase().equals(".doc") &&  !suffix.toLowerCase().equals(".docx") &&  !suffix.toLowerCase().equals(".pdf") ){
                    result.setFlag(false);
                    result.setMsg("请上传doc|docx|pdf文件");
                    return result;
                }
                if (fileName.indexOf("招标") == -1) {
                    result.setFlag(false);
                    result.setMsg("项目招标文件上传的文件名称必须包含“招标”字样");
                    return result;
                }
            } else if ("313".equals(fileData.getType())) {
                if(!suffix.toLowerCase().equals(".doc") &&  !suffix.toLowerCase().equals(".docx") &&  !suffix.toLowerCase().equals(".pdf") ){
                    result.setFlag(false);
                    result.setMsg("请上传doc|docx|pdf文件");
                    return result;
                }
                if (fileName.indexOf("投标") == -1) {
                    result.setFlag(false);
                    result.setMsg("项目投标文档上传的文件名称必须包含“投标”字样");
                    return result;
                }
            } else if ("314".equals(fileData.getType())) {
                if( !suffix.toLowerCase().equals(".pdf") ){
                    result.setFlag(false);
                    result.setMsg("请上传pdf文件");
                    return result;
                }
                if (fileName.indexOf("合同") == -1) {
                    result.setFlag(false);
                    result.setMsg("合同文件上传的文件名称必须包含“合同”字样，且为PDF格式");
                    return result;
                }
            } else if ("315".equals(fileData.getType())) {
                if(!suffix.toLowerCase().equals(".doc") &&  !suffix.toLowerCase().equals(".docx") ){
                    result.setFlag(false);
                    result.setMsg("请上传doc|docx文件");
                    return result;
                }
                if (fileName.indexOf("合同") == -1   ||  fileName.indexOf("说明") == -1 ) {
                    result.setFlag(false);
                    result.setMsg("合同说明文件上传的文件名称必须包含“合同\"和\"说明”字样");
                    return result;
                }
            }
        }
        //对上传文件的基础校验:
        //保存文件
        try {
            File newFile = new File(fileTempPath+newFileName);
            FileUtils.copyInputStreamToFile(file.getInputStream(), newFile);
            //存入缓存表:
            //创建人
            fileData.setCreateBy(CommonUtil.getUserId());
            //创建时间
            fileData.setCreateDate(new Date());
            //文件路径
            fileData.setUrl(newFile.getPath());
            //文件名称
            fileData.setFileName(fileName);
            //文件类型
            fileData.setFileType(suffix);
            //设置知识库类型为文件类型
            fileData.setZskfileType("2");
            //插入
            fileTempService.insertSelective(fileData);
            insertFileLog(fileName);
            if("311".equals(fileData.getType())  || "312".equals(fileData.getType()) || "313".equals(fileData.getType()) || "314".equals(fileData.getType())  || "315".equals(fileData.getType())  ){
                String linkId = fileData.getLinkId();
                if(StringUtil.isNotBlank(linkId)){
                    //
                    SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(linkId);
                    // 001 以保存  002 待审核  003 已驳回 004 已结束  005 已撤销 006 已发布
                    // 项目状态
                    // 提交之后的项目    复制到综合库
                    String status = project.getStatus();
                    if("006".equals(status)){
                        String copyZskUrl = fileTempService.getCopyZskUrl(project);
                        List  listfile=new ArrayList();
                        listfile.add(fileData);
                        fileTempService.updateCopyFileToZsk( copyZskUrl,project,listfile);

                    }
                }


            }
            JSONObject resultData = new JSONObject();
            result.setData(fileData);
            result.setMsg("上传成功");
            result.setFlag(true);
        } catch (IOException e) {
            e.printStackTrace();
            return JsonUtil.error("上传失败");
        }
        return result;
    }

    /**
     * 保存临时文件,并存入临时file表
     * @param file
     * @param fileData 文件参数载体
     * @return
     */
    @ResponseBody
    @PostMapping("/upload/toReal")
    public JsonUtil uploadToReal(MultipartFile file,SupervisorFile fileData){
        JsonUtil result = new JsonUtil();
        String fileName = file.getOriginalFilename();
        //表单核心目录文件id:
        String formCenterFileId = fileData.getLinkId();
        SupervisorFile parentDic = null;
        synchronized (this){
            if(StringUtils.isBlank(formCenterFileId)){
                if(fileData.getType().startsWith("110001") && StringUtils.isNotBlank(fileData.getSuperiorId())){
                    //正中参编标准编辑页面上传文件:
                    parentDic = dicService.selectByPrimaryKey(fileData.getSuperiorId());
                }else{
                    log.warning("编辑表单页面上传文件,没有获取到表单核心文件id");
                    return JsonUtil.error("上传失败");
                }
            }else{
                SupervisorFile formCenterFile = dicService.selectByPrimaryKey(formCenterFileId);
                //查询该文档的父级文件夹:
                SupervisorFile parentDicSelect = new SupervisorFile();
                parentDicSelect.setLinkId(formCenterFileId);
                parentDicSelect.setType(fileData.getType());
                parentDicSelect.setDeleteState("1");
                parentDicSelect.setZskfileType("1");
                List<SupervisorFile> select = dicService.select(parentDicSelect);
                if(CollectionUtil.isEmpty(select)){
                    //这里是第一次创建表单的时候,没有上传对应类型的文件,所以没有文件的对应的文件夹,这里需要创建一下
                    String formTypeCode = fileData.getType().substring(0,6);
                    String formFileTypeCode = fileData.getType();
                    String formFilePath = formBaseService.getFormFilePath(formCenterFile, formTypeCode, formFileTypeCode);
                    if(StringUtils.isNotBlank(formFilePath)){
                        File dicFile = new File(formFilePath);
                        if(!dicFile.exists()){
                            dicFile.mkdirs();
                        }
                        SupervisorFile newDicFile = new SupervisorFile();
                        newDicFile.setId(IdUtil.simpleUUID());
                        newDicFile.setFileName(dicFile.getName());
                        newDicFile.setType(formFileTypeCode);
                        newDicFile.setUrl(dicFile.getPath());
                        newDicFile.setCreateDate(new Date());
                        newDicFile.setCreateBy(CommonUtil.getUserId());
                        newDicFile.setLinkId(formCenterFile.getId());
                        newDicFile.setZskfileType("1");
                        newDicFile.setSuperiorId(formCenterFile.getId());
                        newDicFile.setExamineUser(formCenterFile.getExamineUser());
                        newDicFile.setDownloadUser(formCenterFile.getDownloadUser());
                        newDicFile.setCanotSeeRoles(formCenterFile.getCanotSeeRoles());
                        newDicFile.setDeleteState("1");
                        dicService.insertSelective(newDicFile);
                        select.add(newDicFile);
                    }else{
                        log.warning("编辑表单页面,上传文件,没有查询到目标文件夹");
                        log.warning("formCenterFileId:"+formCenterFileId+",fileType:"+fileData.getType());
                        return JsonUtil.error("上传失败");
                    }
                }
                parentDic = select.get(0);
            }
        }
        String newFilePath = parentDic.getUrl().endsWith(File.separator) ? parentDic.getUrl() + fileName : parentDic.getUrl() + File.separator + fileName;
        File newFile = new File(newFilePath);
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), newFile);
            //保存到数据库:
            //先看看有没有:
            SupervisorFile newSupervisorFileSelect = new SupervisorFile();
            newSupervisorFileSelect.setUrl(newFile.getPath());
            List<SupervisorFile> select = dicService.select(newSupervisorFileSelect);
            SupervisorFile returnFile = null;
            String filename=file.getOriginalFilename();
            if(CollectionUtil.isNotEmpty(select)){
                SupervisorFile sameUrlFile = select.get(0);
                sameUrlFile.setZskfileType("2");
                sameUrlFile.setFileType(fileName.substring(fileName.lastIndexOf(".")));
                sameUrlFile.setSuperiorId(parentDic.getId());
                sameUrlFile.setCreateDate(new Date());
                sameUrlFile.setCreateBy(CommonUtil.getUserId());
                sameUrlFile.setType(fileData.getType());
                sameUrlFile.setDeleteState("1");
                sameUrlFile.setFileName(file.getOriginalFilename());
                dicService.updateByPrimaryKeySelective(sameUrlFile);
                returnFile = sameUrlFile;
            }else{
                SupervisorFile newSupervisorFile = new SupervisorFile();
                newSupervisorFile.setUrl(newFile.getPath());
                newSupervisorFile.setFileType(fileName.substring(fileName.lastIndexOf(".")));
                newSupervisorFile.setSuperiorId(parentDic.getId());
                if(fileData.getType().startsWith("110001")){
                    //正中参编标准,设置文件linkid指向formId
                    newSupervisorFile.setLinkId(fileData.getSpfId());
                }else{
                    newSupervisorFile.setLinkId(formCenterFileId);
                }
                newSupervisorFile.setZskfileType("2");
                newSupervisorFile.setCreateDate(new Date());
                newSupervisorFile.setCreateBy(CommonUtil.getUserId());
                newSupervisorFile.setType(fileData.getType());
                newSupervisorFile.setDeleteState("1");
                newSupervisorFile.setFileName(file.getOriginalFilename());
                dicService.insertSelective(newSupervisorFile);
                returnFile = newSupervisorFile;
            }

            insertFileLog(filename);
            result.setData(returnFile);
            result.setMsg("上传成功");
            result.setFlag(true);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return JsonUtil.error("上传失败");
        }
    }


    //日志
    public void insertFileLog(String filename) {

        SysLog sysLog = new SysLog();
        sysLog.setCreateTime(new Date());
        sysLog.setType("ADD");
        sysLog.setText("上传文件");
        sysLog.setParam("参数:文件名称：" + filename);
        sysLog.setCreateTime(DateUtil.parseDate(DateUtil.getCurrentDateString()));
        CurrentUser currentUser = Principal.getCurrentUse();
        sysLog.setUserName(currentUser.getUsername());
        sysLogMapper.insert(sysLog);
    }

    //日志
    public void deleteFileLog(String filename) {

        SysLog sysLog = new SysLog();
        sysLog.setCreateTime(new Date());
        sysLog.setType("DEL");
        sysLog.setText("删除文件");
        sysLog.setParam("参数:文件名称：" + filename);
        sysLog.setCreateTime(DateUtil.parseDate(DateUtil.getCurrentDateString()));
        CurrentUser currentUser = Principal.getCurrentUse();
        sysLog.setUserName(currentUser.getUsername());
        sysLogMapper.insert(sysLog);
    }

    /**
     * 删除表单临时文件
     * @param fileId
     * @param temp      删除临时为"1"  删除正式为"0"
     * @return
     */
    @ResponseBody
    @PostMapping("/del")
    public JsonUtil delTemp(String fileId,String temp){
        if(StringUtils.isBlank(fileId) || StringUtils.isBlank(temp)){
            return JsonUtil.error("删除失败,参数为空");
        }
        if("1".equals(temp)){
            //新增表单页面的删除:
            SupervisorFileTemp tempFile = fileTempService.selectByPrimaryKey(fileId);
            if(tempFile != null){
                String filePath = tempFile.getUrl();
                if(StringUtils.isNotBlank(filePath)){
                    File wileDelFile = new File(filePath);
                    if(wileDelFile.exists() && wileDelFile.isFile()){
                        boolean delete = wileDelFile.delete();
                        if(!delete){
                            log.warning("删除表单临时上传文件时,删除系统文件失败,filePath:"+filePath);
                            return JsonUtil.error("删除失败");
                        }
                    }
                }
                deleteFileLog(tempFile.getFileName());
            }
            fileTempService.deleteByPrimaryKey(fileId);
            return JsonUtil.sucess("删除成功");
        }else if("0".equals(temp)){
            //编辑表单页面的删除
            //放入回收站:
            SupervisorFile delFile = new SupervisorFile();
            delFile.setId(fileId);
            delFile.setDeleteState("2");
            delFile.setDeleteDate(DateUtil.getCurrentDateString());
            delFile.setDeleteUser(CommonUtil.getUserId());
            SupervisorFile file = dicService.selectByPrimaryKey(fileId);
            if(file!=null){
                deleteFileLog(file.getFileName());
            }

            int i = dicService.updateByPrimaryKeySelective(delFile);
            if(i == 1){
                return JsonUtil.sucess("删除成功");
            }else{
                return JsonUtil.error("删除失败");
            }
        }
        return JsonUtil.error("删除失败");
    }

}
